#include "logic.h"
#include <iostream>

Logic::Logic( ) : player(0), gridSizeX(3), gridSizeY(3)
{
	grid.resize(gridSizeX);
	for (int i = 0; i < gridSizeY; ++i)
		grid[i].resize(gridSizeX);
}

Logic::~Logic( )
{
	grid.clear( );
}

// Initialise the Grid
void Logic::initGrid( void )
{
	int i, j;
	for( i = 0; i < gridSizeX; i++)
		for( j = 0; j < gridSizeY; j++)
			grid[i][j] = " ";
}

// Get a players move
void Logic::getPlayerMove(bool playerIndex )
{
	int x, y;
	std::cout << "Player " << playerIndex + 1 << " " << std::endl;
	std::cout << "Please enter the coordinates of your move: " << std::endl;
	std::cout << "First the X coord(between 1 and " << gridSizeX << "): " << std::endl;
	std::cin >> x;

	// check params
	if(( x <= 0 ) || ( x >= 4))
	{
		std::cout << "This position is not valid." << std::endl;
		getPlayerMove(playerIndex);
	}

	std::cout << "Now the Y coord(between 1 and " << gridSizeY << "): " << std::endl;
	std::cin >> y;

	if(( y <= 0 ) || ( y >= 4))
	{
		std::cout << "This position is not valid." << std::endl;
		getPlayerMove(playerIndex);
	}


	// Remove one from each of the x and y to align with our array space :)
	x--;y--;

	// check the grid position is valid
	if( grid[x][y] != " ")
	{
		std::cout << "This position is not valid." << std::endl;
		getPlayerMove(playerIndex);
	}
	else
	{
		if( playerIndex == 0 )
			grid[x][y] = "X";
		else
			grid[x][y] = "O";
	}
}

void Logic::displayGrid( void ) const
{
	int t;

	for( t = 0; t < gridSizeX; t++)
	{
		std::cout << "  " << grid[t][0] << " | " << grid[t][1] << " | " << grid[t][2] << "  " << std::endl;
		if( t!=2) 
			std::cout << " ---|---|--- " << std::endl;
	}
	std::cout << std::endl;
}

// Check to see if there is a winner
std::string Logic::checkGrid(void)
{
	// check rows
	for( int i = 0; i < gridSizeX; i++)
		if( grid[i][0] == grid[i][1] && grid[i][0] == grid[i][2])
			return grid[i][0];

	// check columns
	for( int i = 0; i < gridSizeY; i++)
		if( grid[0][i] == grid[1][i] && grid[0][i] == grid[2][i])
			return grid[0][i];

	// check diags
	if( grid[0][0] == grid[1][1] && grid[1][1] == grid[2][2])
		return grid[0][0];
	else if( grid[0][2] == grid[1][1] && grid[1][1] == grid[2][0])
		return grid[0][2];

	return " ";
}

